package com.github.defense.plugin.gray.netflix.feign;


import com.github.defense.plugin.gray.constants.GrayClientConstant;
import com.github.defense.plugin.gray.context.RoutingHandler;
import com.github.defense.plugin.gray.context.RoutingLocalContext;
import com.github.defense.plugin.gray.enums.GrayType;
import com.github.defense.plugin.gray.holder.GrayEnvContextHolder;
import com.github.defense.plugin.gray.request.GrayHttpRequest;
import com.github.defense.plugin.gray.utils.WebUtils;
import feign.Client;
import feign.Request;
import feign.Response;

import java.io.IOException;
import java.net.URI;

/**
 * @Author: lettger
 * @Date: 2021/6/20 8:47 下午
 */
public class GrayFeignClient implements Client {

    private Client delegate;

    private RoutingHandler handler;

    public GrayFeignClient(Client delegate, RoutingHandler handler) {
        this.delegate = delegate;
        this.handler = handler;
    }

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        // 未开启灰度
        if(!GrayEnvContextHolder.getEnvBool(GrayClientConstant.GRAY_CLIENT_ENABLE)){
            return delegate.execute(request, options);
        }
        URI uri = URI.create(request.url());
        GrayHttpRequest grayRequest = new GrayHttpRequest();
        grayRequest.setUri(uri);
        grayRequest.setServiceId(uri.getHost());
        grayRequest.setParameters(WebUtils.getQueryParams(uri.getQuery()));
        grayRequest.addHeaders(request.headers());
        grayRequest.setMethod(request.httpMethod().name());
        RoutingLocalContext context = RoutingLocalContext.builder().grayType(GrayType.FEIGN).request(grayRequest).build();
        return handler.execute(context, () -> delegate.execute(request, options));
    }
}
